/*
 * 创建日期 2004-10-29
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.ctsi.commons.util;

 
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * @author Administrator
 * 
 *         更改所生成类型注释的模板为 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public final class Base64 {
 

	public  static byte[] base64Decode(byte[] data) {
		return java.util.Base64.getDecoder().decode(data);
 
	}

	public  static byte[] base64Encode(byte[] data) {
 

		return java.util.Base64.getEncoder().encode(data);
	}

	/**
	 * encode the input data producing a base 64 output stream.
	 * 
	 * @return the number of bytes produced.
	 */
	public  static void encode(byte[] data, int off, int length, OutputStream out) throws IOException {
		OutputStream bout=java.util.Base64.getEncoder().wrap(out);
		bout.write( data,   off,   length);
		
 
	}

 
	/**
	 * 通过jdk解码base 64,写入outputstream
	 *  
	 * 
	 * @return the number of bytes produced.
	 */
	public  static int decode(byte[] data, int off, int length, OutputStream out) throws IOException {
		ByteBuffer needd=ByteBuffer.wrap(data,   off,   length);
		ByteBuffer dbb=java.util.Base64.getDecoder().decode(needd);
		byte[] da=dbb.array();
		out.write(da);
        return da.length;
	}

 

	/**
	 * 解码base64,注意不忽略空白字符,
	 *  
	 * 
	 * @return the number of bytes produced.
	 */
	public  static int decode(final String data, OutputStream out) throws IOException {
		byte[] decb=java.util.Base64.getDecoder().decode(data);
		out.write(decb);
		return decb.length;
	 
	}



	/**
	 * 进行base64解码 specified in RFC-2045 (Section 6.8).
	 * 
	 * @param str
	 *            解码的字符串
	 * @return the decoded 结果.
	 */
	public  static String base64Decode(final String str) {
		if (UtilValidate.isEmpty(str))
			return str;

 
		return new String(java.util.Base64.getDecoder().decode(str));
	}

	public  static String base64Decode(final String str,final  String charsetName) throws UnsupportedEncodingException {
		if (UtilValidate.isEmpty(str))
			return str;

		byte[] data = str.getBytes(charsetName);
		return new String(java.util.Base64.getDecoder().decode(data), charsetName);
	}

	/**
	 * 对字符串进行base64编码 specified in RFC-2045 (Section 6.8).
	 * 
	 * @param str
	 *            编码字符串
	 * @return 编码后字符串
	 */
	public  static String base64Encode(final String str) {
		if (UtilValidate.isEmpty(str))
			return str;

		byte data[] = str.getBytes();
		return new String(java.util.Base64.getEncoder().encode(data));
	}

	public  static String base64Encode(final String str,final  String charsetName) throws UnsupportedEncodingException {
		if (UtilValidate.isEmpty(str))
			return str;

		byte data[] = str.getBytes(charsetName);
		return new String(java.util.Base64.getEncoder().encode(data),charsetName);
	}
}
